package com.gjp.controller;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.gjp.bean.Query;
import com.gjp.entity.Customer;
import com.gjp.entity.Dictionary;
import com.gjp.service.CustomerService;
import com.gjp.service.DictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by gjp on 2017-6-5.
 */
@RestController
@RequestMapping("/customer")
public class CustomerController {

    @Autowired
    private CustomerService customerService;
    @Autowired
    private DictionaryService dictionaryService;

    //返回页面
    private String viewName="/customer/customer";
    //字典数据
    private List<Dictionary> dictionaries;
    //高级查询字典
    List<Dictionary> source;
    List<Dictionary> industry;
    List<Dictionary> level;
    //高级查询条件  默认初始化为空
    private Query query = new Query();
    //每页显示条数
    Integer pageSize = 6;

    /**
     * 首页
     * @return
     */
    @GetMapping("/index")
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView(viewName);
        //初始化分页条件查询数据，初始不需要查询条件
        Page<Customer> pages = getPages(1, null);
        modelAndView.addObject("pages", pages);
        setRetData(modelAndView);
        return modelAndView;
    }

    /**
     * 高级查询
     * @param query
     * @return
     */
    @PostMapping("/query")
    public ModelAndView query(Query query) {
        ModelAndView modelAndView = new ModelAndView(viewName);
        this.query = query;
        //组查询条件
        EntityWrapper<Customer> wrapper = getQueryWrapper();
        //执行条件分页查询
        Page<Customer> pages = getPages(1, wrapper);
        modelAndView.addObject("pages", pages);
        setRetData(modelAndView);
        return modelAndView;
    }

    /**
     * 分页
     * @return
     */
    @GetMapping("/page/{page}")
    public ModelAndView page(@PathVariable("page") Integer page) {
        ModelAndView modelAndView = new ModelAndView(viewName);
        Page<Customer> pages = getPages(page, getQueryWrapper());
        modelAndView.addObject("pages", pages);
        setRetData(modelAndView);
        return modelAndView;
    }

    /**
     * 获取客户详细信息
     * @param id
     * @return
     */
    @PostMapping("/detail")
    public Customer detail(Long id) {
        Customer customer = customerService.selectById(id);
        return customer;
    }

    /**
     * 更新 或 添加客户
     * @return
     */
    @PostMapping("/update")
    public boolean update(Customer customer) {
        if (customer.getCreatetime()==null){
            customer.setCreatetime(new Date());
        }
        boolean b = customerService.insertOrUpdate(customer);
        return b;
    }

    /**
     * 删除客户
     * @return
     */
    @PostMapping("/delete")
    public boolean update(Long id) {
        boolean b = customerService.deleteById(id);
        return b;
    }
    /*---------------------------------以上为controller层---------------------------------------*/














    /*---------------------------------以下为自定义方法---------------------------------------*/
    /**
     * 初始化必要数据
     */
    private void init() {
        if (dictionaries == null) {
            //初始化字典
            initDictionary();
        }
    }
    //初始化字典
    public void initDictionary() {
        if (dictionaries != null) {
            return;
        }
        dictionaries = dictionaryService.selectList(new EntityWrapper<Dictionary>()
                .eq("onoff", "1")   //只查询有效状态为1的记录
        );
        //初始化高级查询
        initQuery();
    }
   //根据数据字典，初始化高级查询
    private void initQuery() {
        source = new ArrayList<>();
        industry = new ArrayList<>();
        level = new ArrayList<>();
        for (Dictionary d : dictionaries) {
            //客户来源 002
            if ("002".equals(d.getTypecode())) {
                source.add(d);
            }
            //客户行业 001
            if ("001".equals(d.getTypecode())) {
                industry.add(d);
            }
            //客户级别 006
            if ("006".equals(d.getTypecode())) {
                level.add(d);
            }
        }
    }

    /**
     * 分页查询
     * @param currentPage   当前页数
     * @param wrapper       查询条件
     * @return
     */
    private Page<Customer> getPages(Integer currentPage, Wrapper<Customer> wrapper) {
        //初始化必要数据
        init();
        //分页条件查询
        Page<Customer> pages = customerService.selectPage(
                //默认查10条，可以在这里修改，也可以做传入参数
                new Page<Customer>(currentPage, pageSize),
                wrapper
        );
        //转换字典数据
        canvertData(pages);
        return pages;
    }

    /**
     * 转换字典数据
     * @param customers
     */
    private void canvertData(Page<Customer> customers) {
        //查询出来的数据，将字典标示替换为字典中的详细说明
        for (Customer c : customers.getRecords()) {
            for (Dictionary d : dictionaries) {
                if (c.getSource().equals(d.getUid())) {
                    c.setSource(d.getItemname());
                }
                if (c.getIndustry().equals(d.getUid())) {
                    c.setIndustry(d.getItemname());
                }
                if (c.getLevel().equals(d.getUid())) {
                    c.setLevel(d.getItemname());
                }
            }
        }
    }
    /**
     * 通用数据回显
     */
    private void setRetData(ModelAndView modelAndView) {
        modelAndView.addObject("source", source);
        modelAndView.addObject("industry", industry);
        modelAndView.addObject("level", level);
        modelAndView.addObject("query", query);
    }
    /**
     * 根据当前存储的query，组查询条件
     */
    private EntityWrapper<Customer> getQueryWrapper() {
        EntityWrapper<Customer> wrapper = new EntityWrapper<>();
        if (null != query.getName() && !"".equals(query.getName())) {
            wrapper.like("name", query.getName(), SqlLike.DEFAULT);
        }
        if (null != query.getSource() && !"".equals(query.getSource())) {
            wrapper.eq("source", query.getSource());
        }
        if (null != query.getIndustry() && !"".equals(query.getIndustry())) {
            wrapper.eq("industry", query.getIndustry());
        }
        if (null != query.getLevel() && !"".equals(query.getLevel())) {
            wrapper.eq("level", query.getLevel());
        }
        return wrapper;
    }
}
